#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <errno.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define MAX_EVENT 50
#define MAX_SIZE 512

static int setnonblocking(int fd) {
    // 获取
    int old_option = fcntl(fd, F_GETFL);
    int new_option = old_option | O_NONBLOCK;
    fcntl(fd, F_SETFL, new_option);
    return old_option;
}

static void addfd(int epollfd, int fd) {
    struct epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN | EPOLLET;
    epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
    setnonblocking(fd);
}

//从epollfd标识的epoll内核事件表中删除fd上的所有注册事件
static void removefd(int epollfd, int fd) {
    epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, 0);
    close(fd);
}

int main(int argc, char **argv) {
    if (argc != 2) {
        printf("Usage: %s <port>\n", argv[0]);
        return 0;
    }
    int server_fd = socket(PF_INET, SOCK_STREAM, 0);
    assert(server_fd != -1);
    struct sockaddr_in addr, client_addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(atoi(argv[1]));

    
    int rc = bind(server_fd, (struct sockaddr *)&addr, sizeof(addr));
    assert(rc != -1);
    
    listen(server_fd, 5);
    int epfd = epoll_create(5);
    struct epoll_event event[MAX_EVENT];
    addfd(epfd, server_fd);
//    setnonblocking(server_fd);

    while (1) {
        int event_cnt = epoll_wait(epfd, event, MAX_EVENT, -1);
        puts("epoll wait()");
        if (event_cnt == -1) {
            break;
        }
        for (int i = 0; i < event_cnt; i++) {
            struct epoll_event e = event[i];
            if (e.data.fd == server_fd) {
                int len = sizeof(client_addr);
                int connfd = accept(server_fd, (struct sockaddr *)&client_addr, &len);
                printf("conncet ... %d\n", connfd);
                addfd(epfd, connfd);
            } else {
                while (1) {
                    char buf[MAX_SIZE] = {0};
                    int len = read(event[i].data.fd, buf, MAX_SIZE);
                    if (len == 0) {
                        printf("disconnect ... %d\n", event[i].data.fd);
                        removefd(epfd, event[i].data.fd);
                        break;
                    } else if (len < 0) {
                        if (errno == EAGAIN)
                            break;
                    } else {
                        write(event[i].data.fd, buf, MAX_SIZE);
                    }
                }
            }
        }
    }
    close(server_fd);
    return 0;
}